package com.RateLimiter;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static java.lang.Thread.currentThread;

/**
 * Created by Lxk on 2019/5/3.
 */
public class TokenBucket {

    private AtomicInteger phoneNumbers = new AtomicInteger(0);

    private final static int LIMIT = 100;

    private RateLimiter rateLimiter = RateLimiter.create(10);

    private final int saleLimit;

    public TokenBucket(){
        this(LIMIT);
    }

    public TokenBucket(int limit){
        this.saleLimit = limit;
    }

    public int buy(){
        boolean success = rateLimiter.tryAcquire(10, TimeUnit.SECONDS);
        if(success){
            if(phoneNumbers.get() >= saleLimit){
                throw new IllegalStateException("No phone remained");
            }
            int phoneNo = phoneNumbers.getAndIncrement();
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(currentThread() + " get mi phone, num is " +phoneNo);
        }else{
            throw new RuntimeException("fail to get phone");
        }
        return 0;
    }

}
